package org.bugeden.netdisk.json

import java.util.Date
import com.google.gson._
import java.lang.reflect.Type
import java.text.SimpleDateFormat
import org.bugeden.netdisk.common.Std

/**
 * Created by IntelliJ IDEA.
 * User: inotseeyou
 * Date: 2010-11-11
 * Time: 23:40:50
 * To change this template use File | Settings | File Templates.
 */

trait Json{

  def toJson = {
    Json.toJson(this)
  }
}

object Json{
  val gsonBuilder = new GsonBuilder()
  
  val gson = {
    gsonBuilder.registerTypeAdapter(classOf[Date], new DateTimeConverter)
    gsonBuilder.create
  }
  
  def fromJson[T](jsonStr: String, clazz: Class[T]): T = {
    gson.fromJson(jsonStr, clazz)
  }

  def toJson(any: AnyRef): String = {
    gson.toJson(any)
  }

  class DateTimeConverter extends AnyRef with JsonSerializer[Date] with JsonDeserializer[Date]{
    def serialize(date: Date, t: Type, context: JsonSerializationContext): JsonElement = {
      new JsonPrimitive(Std.datetimeFormat.format(date))
    }

    def deserialize(json: JsonElement, t: Type, context: JsonDeserializationContext) = {
      Std.datetimeFormat.parse(json.getAsJsonPrimitive.getAsString);
    }
  }
}